package com.xmy.cultivate.controller;

import com.aliyun.facebody20191230.models.AddFaceResponse;
import com.aliyun.facebody20191230.models.SearchFaceResponse;
import com.aliyun.facebody20191230.models.SearchFaceResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.request.DetectFaceDataRequest;
import com.xmy.cultivate.entity.request.FaceDetectLivingRequest;
import com.xmy.cultivate.entity.views.AiSitePcLoginRs;
import com.xmy.cultivate.entity.views.FaceResult;
import com.xmy.cultivate.entity.views.SignResult;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/face")
@Scope("prototype")
public class FaceController extends BaseController {

    @Value("${aliyun.AccessKeyID}")
    String accessKeyId;

    @Value("${aliyun.AccessKeySecret}")
    String accessKeySecret;

    @Value("${aliyun.oss.endpoint}")
    String ossEndpoint;

    @Value("${aliyun.oss.showImgEndpoint}")
    String showImgEndpoint;



    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**

    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IAliyunFaceService iAliyunFaceService;

    @Autowired
    @Lazy
    IOssUploadService iOssUploadService;

    @Autowired
    @Lazy
    IStudentFaceDataService iStudentFaceDataService;

    @Autowired
    @Lazy
    IStudentSignInService iStudentSignInService;

    @Autowired
    @Lazy
    IStudentSignInTempService iStudentSignInTempService;

    @Autowired
    @Lazy
    IFaceDbService iFaceDbService;

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;


    @Autowired
    @Lazy
    IWecharsBindService iWecharsBindService;

    @Autowired
    @Lazy
    IFaceStudentService iFaceStudentService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    ILogRecordService iLogRecordService;

    @Autowired
    @Lazy
    IRepairCourseService iRepairCourseService;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    IStudentFaceManyService iStudentFaceManyService;

    @Autowired
    @Lazy
    IStudentFaceManyDetailService iStudentFaceManyDetailService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    IStudentAudioService iStudentAudioService;

    @Autowired
    @Lazy
    ICompanyService iCompanyService;

    @Autowired
    @Lazy
    IAiSchoolSiteService iAiSchoolSiteService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;
    @Autowired
    private StaffMapper staffMapper;

    @Autowired //如果给redis中保存数据会使用默认的序列化机制，导致redis中保存的对象不可视
    RedisTemplate<Object, Object> redisTemplate;


    @GetMapping("/getSiginSubjects")
    public Result getSiginSubjects(){
        Integer lessonType =1;
        List<String> stringList = iStaffService.getSiginSubjects(this.staffInfo,lessonType);
        //1带班老师，0非带班老师
        Integer teacherType = iStaffService.getSiginSubjectsType(this.staffInfo,lessonType);
        return new Result(Code.OK,stringList,teacherType.toString());
    }


    /**
     * 签到
     *
     * @return
     */
    @PostMapping("/signIn")
    public Result signIn(@RequestParam("file") MultipartFile upload, HttpServletRequest request,
                         @RequestParam(value = "schoolId",required = false) Long schoolId,
                         @RequestParam(value = "subjectsId",required = false) String subjectsId,
                         @RequestParam(value = "adminId",required = false) Long adminIdParam,
                         @RequestParam(value = "schoolSiteId",required = false) String schoolSiteId
    ) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

        if (adminIdParam != null){
            this.adminId = adminIdParam;
        }

        if(quarterNow == null){
            throw new CommonException(ResultCode.quarterNo);
        }

        Integer lessonType =1;
        Staff staff = iStaffService.getOneById(this.adminId);
        if (StringUtils.isBlank(subjectsId)){
            List<String> stringList = iStaffService.getSiginSubjects(staff,lessonType);
            if (stringList.size() ==1){
                subjectsId = stringList.get(0);
            }else {
                return new Result(Code.ERROR, "", "请先选择签到的科目");
            }
        }
        //非任课老师
        if (!staff.getIsTeacher().equals(1)){
            if (subjectsId.equals("1")){
                lessonType = 2;//智能课
            }else{
                lessonType = 3;//刷题班
            }
        }
        //是否需要人脸数据校验
        Company company = iCompanyService.getById(1L);
        boolean IsFaceDataVerify = false;
        if (company!=null){
            if (company.getIsFaceDataVerify().equals(1) || company.getIsFaceDataVerify().equals(2)){
                IsFaceDataVerify = true;
            }
        }

        Map<String, Object> mapResult = new HashMap<>();
        String ossImageUrl = "";

        //随机获取出一个校区
        Organization schoolRand = iOrganizationService.getOneRand();
        Long schoolIdForFace = schoolRand.getId();

        try {
            /*Organization schoolInfo = null;
            if (StringUtils.isEmpty(schoolId)) {
                return new Result(Code.ERROR, "", "学校id不能为空");
            } else {
                schoolInfo = iOrganizationService.getById(schoolId);
                if (schoolInfo == null) {
                    return new Result(Code.ERROR, "", "学校不存在");
                }
            }*/

            if (upload == null || upload.isEmpty()) {
                return new Result(Code.ERROR, "", "没有上传文件，请关闭重新打开");
            }
            LocalDate localDate = LocalDate.now();
            LocalDateTime localDateTime = LocalDateTime.now().withNano(0);

            FaceDb faceDb = iFaceDbService.getFaceDbOne(1);

            //上传文件的位置,默认会在项目根目录找static文件夹,需手动创建,不然找到是临时路径。
            //String path = request.getSession().getServletContext().getRealPath("/uploads/header");
            //System.out.println("path:"+path);
            //判断该路径是否存在

            String directoryName = "face-sign" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();//签到图片目录
            String uploadUrl = uploadFileLocation + "/" + directoryName;
            File file = new File(uploadUrl);
            // 若不存在则创建该文件夹
            if (!file.exists()) {
                file.mkdirs();
            }
            //获取上传文件的后缀名
            String fileType = upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
            // 获取上传文件的名称
            //String filename = upload.getOriginalFilename();
            // 把文件的名称设置唯一值，uuid
            //拼接图片
            String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
            String uuid = date + System.currentTimeMillis();
            String filename = uuid + fileType;
            // todo 把文件名存入数据库(此步骤省略)
            mapResult.put("signDateTime", localDateTime.toString().replace("T", " "));
            // 完成文件上传

            upload.transferTo(new File(uploadUrl, filename));
            String filePath = uploadUrl + "/" + filename;
            String saveName = filename;

            boolean ossUpRs = iOssUploadService.upFile(filePath, saveName, directoryName);//上传到oss

            Long recordCourseId = 0L;
            if (ossUpRs) {
                ossImageUrl = this.showImgEndpoint + "/" + directoryName + "/" + saveName;

                //System.out.println("ossImageUrl:"+ossImageUrl);
                SearchFaceResponse searchFaceResponse = iAliyunFaceService.searchFace(faceDb.getDbName(), schoolIdForFace, ossImageUrl);
                if (searchFaceResponse.getBody().getData() == null) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10008");
                    mapResult.put("signResult", "考勤失败");
                    return new Result(Code.FACE_ERROR, mapResult, "签到失败,没有找到人脸数据，请重新采集");
                }

                String faceRequestId = searchFaceResponse.getBody().getRequestId();
                List<SearchFaceResponseBody.SearchFaceResponseBodyDataMatchList> searchFaceResponseBodyDataMatchList = searchFaceResponse.getBody().getData().getMatchList();
                if (searchFaceResponseBodyDataMatchList.size() > 0) {
                    SearchFaceResponseBody.SearchFaceResponseBodyDataMatchList faceResponseBodyDataMatchList = searchFaceResponseBodyDataMatchList.get(0);
                    Float QualitieScore = faceResponseBodyDataMatchList.getQualitieScore();
                    Float confidence = Float.parseFloat("70.62");//转换后的置信度
                    Float score = Float.parseFloat("0.6");//人脸的相似度

                    Float maxConfidence = Float.parseFloat("0");
                    Float maxScore = Float.parseFloat("0");

                    SearchFaceResponseBody.SearchFaceResponseBodyDataMatchListFaceItems findFaceResponseBodyDataMatchListFaceItem = null;
                    for (SearchFaceResponseBody.SearchFaceResponseBodyDataMatchListFaceItems searchFaceResponseBodyDataMatchFaceItems : faceResponseBodyDataMatchList.getFaceItems()) {
                        if (findFaceResponseBodyDataMatchListFaceItem == null) {
                            findFaceResponseBodyDataMatchListFaceItem = searchFaceResponseBodyDataMatchFaceItems;
                        } else {
                            //System.out.println("searchFaceResponseBodyDataMatchFaceItems.getConfidence:"+searchFaceResponseBodyDataMatchFaceItems.getConfidence());
                            if (findFaceResponseBodyDataMatchListFaceItem != null && searchFaceResponseBodyDataMatchFaceItems.getConfidence() > findFaceResponseBodyDataMatchListFaceItem.getConfidence()) {
                                findFaceResponseBodyDataMatchListFaceItem = searchFaceResponseBodyDataMatchFaceItems;
                            }
                        }
                    }
                    if (findFaceResponseBodyDataMatchListFaceItem != null) {
                        maxConfidence = findFaceResponseBodyDataMatchListFaceItem.getConfidence();
                        maxScore = findFaceResponseBodyDataMatchListFaceItem.getScore();
                    }

                    if (findFaceResponseBodyDataMatchListFaceItem != null && findFaceResponseBodyDataMatchListFaceItem.getConfidence() >= confidence && findFaceResponseBodyDataMatchListFaceItem.getScore() > score) {
                        String entityId = findFaceResponseBodyDataMatchListFaceItem.getEntityId();
                        findFaceResponseBodyDataMatchListFaceItem.getFaceId();
                        findFaceResponseBodyDataMatchListFaceItem.getScore();
                        findFaceResponseBodyDataMatchListFaceItem.getExtraData();

                        Student student = null;
                        //找到的学生
                        List<Student> studentList = new ArrayList<>();

                        //======================================设置redis，添加到缓存开始================================================
                        String studentSignInManyKey = "studentSignInMany::"+entityId;
                        Object studentSignInManyObj = redisTemplate.opsForValue().get(studentSignInManyKey);
                        if (Objects.isNull(studentSignInManyObj)) {
                            QueryWrapper<StudentFaceManyDetail> studentFaceManyQueryWrapper = new QueryWrapper<>();
                            studentFaceManyQueryWrapper.eq("entity_id", entityId);
                            //studentFaceManyQueryWrapper.eq("ali_account", schoolRand.getAliAccount());
                            //studentFaceManyQueryWrapper.groupBy("ali_account","student_id");
                            studentFaceManyQueryWrapper.orderByDesc("created_at");
                            //studentFaceDataQueryWrapper.eq("school_id",schoolId);
                            List<StudentFaceManyDetail> studentFaceDataList = iStudentFaceManyDetailService.list(studentFaceManyQueryWrapper);
                            for (StudentFaceManyDetail studentFaceMany : studentFaceDataList) {
                                student = iStudentService.getById(studentFaceMany.getStudentId());
                                if(student == null){
                                    continue;
                                }
                                studentList.add(student);
                            }
                            if (studentList.size()>0){
                                redisTemplate.opsForValue().set(studentSignInManyKey,studentList,6, TimeUnit.SECONDS);
                            }
                        }else {
                            studentList = (List<Student>) studentSignInManyObj;
                        }
                        //======================================设置redis，添加到缓存结束================================================

                        if (student == null) {
                            //不在同指定的校区，暂时注释
                            //student = studentNotSchool;
                            //findStudentFaceData = findStudentFaceDataNotSchool;
                        }

                        if (studentList.size() > 0) {
                            /**
                             * 会存在多个学生，添加的查询
                             * 获取排课信息
                             */
                            FaceGetScheduling faceGetScheduling = null;
                            FaceGetScheduling faceGetSchedulingNext = null;
                            for (Student studentInfo : studentList) {
                                if (faceGetScheduling == null) {
                                    student = studentInfo;
                                    faceGetScheduling = iFaceStudentService.getCourseSchedulingDetail(schoolId,this.adminId, studentInfo.getId(),subjectsId,lessonType,quarterNow);
                                    faceGetScheduling.setStudentId(studentInfo.getId());
                                    mapResult.put("name", studentInfo.getName());
                                    mapResult.put("id", studentInfo.getId());
                                    mapResult.put("studentId", studentInfo.getId());
                                    List<StudentAudio> studentAudioList = iStudentAudioService.getListForStudentId(studentInfo.getId());
                                    mapResult.put("nameAudioList", studentAudioList);

                                    if (studentInfo.getHeadImg().isEmpty()) {
                                        mapResult.put("imageUrl", ossImageUrl);
                                    } else {
                                        mapResult.put("imageUrl", studentInfo.getHeadImg());
                                    }
                                } else if (faceGetScheduling.getIsToNext()) {
                                    faceGetSchedulingNext = iFaceStudentService.getCourseSchedulingDetail(schoolId,this.adminId, studentInfo.getId(),subjectsId,lessonType,quarterNow);
                                    if (faceGetSchedulingNext.getType() != null) {
                                        student = studentInfo;
                                        faceGetScheduling = faceGetSchedulingNext;
                                        faceGetScheduling.setStudentId(studentInfo.getId());
                                        mapResult.put("name", studentInfo.getName());
                                        mapResult.put("id", studentInfo.getId());
                                        mapResult.put("studentId", studentInfo.getId());
                                        List<StudentAudio> studentAudioList = iStudentAudioService.getListForStudentId(studentInfo.getId());
                                        mapResult.put("nameAudioList", studentAudioList);
                                        if (studentInfo.getHeadImg().isEmpty()) {
                                            mapResult.put("imageUrl", ossImageUrl);
                                        } else {
                                            mapResult.put("imageUrl", studentInfo.getHeadImg());
                                        }
                                    }
                                }
                            }

                            //System.out.println("=========================================");
                            //System.out.println(faceGetScheduling);
                            if (faceGetScheduling == null || faceGetScheduling.getStatus() == null|| faceGetScheduling.getType() == null) {
                                if (lessonType.equals(2) || lessonType.equals(3)){
                                    //如果签到的是刷题班没有排课信息，添加临时上课信息
                                    faceGetScheduling = iStudentSignInService.getTemporaryData(student.getId(), subjectsId,lessonType,quarterNow);
                                }else if (lessonType.equals(1)){
                                    //签到是精品课，学生为试听类型，添加试听信息
                                    faceGetScheduling = iStudentSignInService.getTryListenData(student,subjectsId,lessonType,quarterNow);
                                }
                            }
                            if (faceGetScheduling == null || faceGetScheduling.getStatus() == null|| faceGetScheduling.getType() == null) {
                                mapResult.put("signCode", "10003");
                                mapResult.put("imageUrl", ossImageUrl);
                                mapResult.put("signResult", "考勤失败");
                                if (lessonType.equals(1)){
                                    return new Result(Code.FACE_ERROR, mapResult, "没有找到现在要签到的排课信息");
                                }else {
                                    return new Result(Code.FACE_ERROR, mapResult, "精品课没有在读科目，签到失败");
                                }
                            }else {
                                FaceDetectLivingRequest faceDetectLivingRequest = iAliyunFaceService.detectLivingFace(schoolId,ossImageUrl);
                                if (!faceDetectLivingRequest.isLiving()){
                                    LogRecord logRecord = new LogRecord();
                                    logRecord.setContent("ossUrl:" + ossImageUrl);
                                    logRecord.setRemark("人脸签到失败，不能使用照片签到"+faceDetectLivingRequest.getScore());
                                    logRecord.setLevel(5);
                                    iLogRecordService.save(logRecord);
                                    if (IsFaceDataVerify){
                                        mapResult.put("imageUrl", ossImageUrl);
                                        mapResult.put("signCode", "10003");
                                        mapResult.put("signResult", "考勤失败");
                                        return new Result(Code.FACE_ERROR, mapResult, "不能使用照片签到，或换个背景签到");
                                    }
                                }
                            }

                            //获取班型
                            Grade grade = iStudentGradeService.getClassTypeNameForStudentId(faceGetScheduling.getYearPart(),faceGetScheduling.getQuarterNum(),faceGetScheduling.getStudentId(),faceGetScheduling.getSubjectsId());
                            String classTypeName = "";
                            String teacherName = "";
                            String yearClassId = "";
                            if (grade !=null){
                                classTypeName = grade.getCourseTypeName();
                                teacherName = grade.getTeacherName();
                                if (grade.getYearClassId() != null){
                                    yearClassId = grade.getYearClassId().getKey().toString();
                                }
                            }
                            mapResult.put("classTypeName",classTypeName);
                            mapResult.put("teacherName",teacherName);
                            mapResult.put("gradeName", faceGetScheduling.getGradeName());
                            mapResult.put("subjectsId",faceGetScheduling.getSubjectsId());
                            mapResult.put("lessonType",faceGetScheduling.getLessonType());
                            mapResult.put("yearClassId",yearClassId);
                            //1签到，2是签退，3交卷
                            Integer signType = 1;

                            //type:1：签到，2：签退，3：已签到，4：已签退，5：还未到签到时间，6：还未到签退时间,7：超过签退时间,8：刷题交卷，9：签到20分钟后交卷时间,10：交卷后5分钏才对签退，11：已交卷
                            if (faceGetScheduling.getType().equals(1) && faceGetScheduling.getStatus().equals(1)) {
                                signType = 1;
                                //添加到记上课表里
                                //if(faceGetScheduling.getCourseType().equals(1)){
                                //    iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(),student.getId(),1,faceGetScheduling.getCourseType());
                                //}
                                if(!faceGetScheduling.getCourseType().equals(7) && !faceGetScheduling.getCourseType().equals(8)){
                                    iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(), student.getName(), 1, faceGetScheduling.getCourseType(), faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,schoolSiteId);
                                    //补、调、消课、缺课补课改为到课状态
                                    if (faceGetScheduling.getCourseType() != null) {
                                        if (faceGetScheduling.getCourseType() == 3 || faceGetScheduling.getCourseType() == 4 || faceGetScheduling.getCourseType() == 5 || faceGetScheduling.getCourseType() == 6) {
                                            RepairCourse repairCourse = iRepairCourseService.getById(faceGetScheduling.getSchedulingDetailId());
                                            if (repairCourse != null) {
                                                repairCourse.setIsSignIn(1);
                                                iRepairCourseService.updateById(repairCourse);
                                            }
                                        }
                                    }
                                    if (faceGetScheduling.getSubjectsId() != null){
                                        Integer lessonTypeAllot = 2;
                                        if(faceGetScheduling.getSubjectsId().equals(1L)){
                                            lessonTypeAllot = 2;
                                        }else if (faceGetScheduling.getSubjectsId().equals(2L)){
                                            //3，4年级
                                            if (yearClassId.equals("3") || yearClassId.equals("4")){
                                                lessonTypeAllot =3;
                                            }
                                        }
                                        RecordCourse recordCourseAdd = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId,student.getId(), student.getName(), 1,faceGetScheduling.getCourseType(),faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,faceGetScheduling.getSubjectsId().toString(),lessonTypeAllot);
                                        LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                                        recordCourseId = recordCourseAdd.getId();
                                        //推送到英语或数学学习系统分配电脑
                                        iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(),faceGetScheduling.getStudentId(),student.getName(),signType,schoolSiteId,this.adminId,kickOutTime);
                                    }
                                }else if (faceGetScheduling.getCourseType().equals(7)){
                                    //智能课或者刷题班临时上课
                                    iRecordCourseService.addTemporaryData(faceGetScheduling,quarterNow,this.adminId,signType,schoolSiteId);
                                    //推送到英语学习系统分配电脑
                                    if (faceGetScheduling.getSubjectsId() != null){
                                        Integer lessonTypeAllot = 2;
                                        if(faceGetScheduling.getSubjectsId().equals(1L)){
                                            lessonTypeAllot = 2;
                                        }else if (faceGetScheduling.getSubjectsId().equals(2L)){
                                            //3，4年级
                                            if (yearClassId.equals("3") || yearClassId.equals("4")){
                                                lessonTypeAllot =3;
                                            }
                                        }
                                        RecordCourse recordCourseAdd  = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId,student.getId(), student.getName(), 1,faceGetScheduling.getCourseType(),faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,faceGetScheduling.getSubjectsId().toString(),lessonTypeAllot);
                                        LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                                        recordCourseId = recordCourseAdd.getId();
                                        //推送到英语学习系统分配电脑
                                        iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(),faceGetScheduling.getStudentId(),student.getName(),signType,schoolSiteId,this.adminId,kickOutTime);
                                    }
                                }else if (faceGetScheduling.getLessonType().equals(1) && faceGetScheduling.getCourseType().equals(8)){
                                    //精品课试听
                                    iRecordCourseService.addTryListenData(faceGetScheduling,quarterNow,this.adminId);
                                }

                            } else if (faceGetScheduling.getType().equals(2) && faceGetScheduling.getStatus().equals(1)) {
                                signType = 2;
                                Long recordCourseId1 = null;
                                //if(faceGetScheduling.getCourseType().equals(1)) {
                                //    iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(), 1,faceGetScheduling.getCourseType());
                                //}
                                if (!faceGetScheduling.getCourseType().equals(7)) {
                                    recordCourseId1 = iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(), student.getName(), 1, faceGetScheduling.getCourseType(), faceGetScheduling.getReachType(), this.adminId, dateTimeNow, signType, schoolSiteId);
                                    //补、调、消课、缺课补课改为到课状态
                                    if (faceGetScheduling.getCourseType() != null) {
                                        if (faceGetScheduling.getCourseType() == 3 || faceGetScheduling.getCourseType() == 4 || faceGetScheduling.getCourseType() == 5 || faceGetScheduling.getCourseType() == 6) {
                                            RepairCourse repairCourse = iRepairCourseService.getById(faceGetScheduling.getSchedulingDetailId());
                                            if (repairCourse != null) {
                                                repairCourse.setIsSignIn(1);
                                                iRepairCourseService.updateById(repairCourse);
                                            }
                                        }
                                    }
                                } else if (faceGetScheduling.getCourseType().equals(7)) {
                                    //临时上课
                                    recordCourseId1 = iRecordCourseService.addTemporaryData(faceGetScheduling, quarterNow, this.adminId, signType, schoolSiteId);
                                    //推送到英语学习系统分配电脑
                                    //推送到英语学习系统分配电脑
                                    if (faceGetScheduling.getSubjectsId() != null) {
                                        Integer lessonTypeAllot = 2;
                                        if (faceGetScheduling.getSubjectsId().equals(1L)) {
                                            lessonTypeAllot = 2;
                                        } else if (faceGetScheduling.getSubjectsId().equals(2L)) {
                                            //3，4年级
                                            if (yearClassId.equals("3") || yearClassId.equals("4")) {
                                                lessonTypeAllot = 3;
                                            }
                                        }
                                        RecordCourse recordCourseAdd = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId, student.getId(), student.getName(), 1, faceGetScheduling.getCourseType(), faceGetScheduling.getReachType(), this.adminId, dateTimeNow, signType, faceGetScheduling.getSubjectsId().toString(), lessonTypeAllot);
                                        LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                                        recordCourseId = recordCourseAdd.getId();
                                        //推送到英语学习系统分配电脑//推送到英语学习系统分配电脑
                                        iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(), faceGetScheduling.getStudentId(), student.getName(), signType, schoolSiteId, this.adminId, kickOutTime);
                                    }
                                } else if (faceGetScheduling.getLessonType().equals(1) && faceGetScheduling.getCourseType().equals(8)) {
                                    //精品课试听
                                    iRecordCourseService.addTryListenData(faceGetScheduling, quarterNow, this.adminId);
                                }

                                mapResult.put("recordCourseId", recordCourseId1);

                            }else if (faceGetScheduling.getType().equals(3) && faceGetScheduling.getStatus().equals(1)) {
                                //推送到英语学习系统分配电脑
                                if (faceGetScheduling.getSubjectsId() != null){
                                    Integer lessonTypeAllot = 2;
                                    if(faceGetScheduling.getSubjectsId().equals(1L)){
                                        lessonTypeAllot = 2;
                                    }else if (faceGetScheduling.getSubjectsId().equals(2L)){
                                        //3，4年级
                                        if (yearClassId.equals("3") || yearClassId.equals("4")){
                                            lessonTypeAllot =3;
                                        }
                                    }
                                    RecordCourse recordCourseAdd = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId,student.getId(), student.getName(), 1,faceGetScheduling.getCourseType(),faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,faceGetScheduling.getSubjectsId().toString(),lessonTypeAllot);
                                    LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                                    recordCourseId = recordCourseAdd.getId();
                                    //推送到英语学习系统分配电脑//推送到英语学习系统分配电脑
                                    iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(),faceGetScheduling.getStudentId(),student.getName(),signType,schoolSiteId,this.adminId,kickOutTime);
                                }
                                mapResult.put("signCode", "10004");
                                mapResult.put("signResult", "签到成功");
                                return new Result(Code.FACE_ERROR, mapResult,  ",签到成功");
                            } else if (faceGetScheduling.getType().equals(4) && faceGetScheduling.getStatus().equals(1)) {
                                mapResult.put("signCode", "10002");
                                mapResult.put("signResult", "签退成功");
                                return new Result(Code.FACE_ERROR, mapResult, "今日已经刷脸签退，不要重复刷脸");
                            } else if (faceGetScheduling.getType().equals(5) && faceGetScheduling.getStatus().equals(1)) {
                                mapResult.put("signCode", "10006");
                                mapResult.put("signResult", "考勤失败");
                                return new Result(Code.FACE_ERROR, mapResult, ",还未到签到时间");
                            } else if (faceGetScheduling.getType().equals(6) && faceGetScheduling.getStatus().equals(1)) {
                                mapResult.put("signCode", "10021");
                                mapResult.put("signResult", "考勤失败");
                                return new Result(Code.FACE_ERROR, mapResult, ",还未到签退时间");
                            } else if (faceGetScheduling.getType().equals(7) && faceGetScheduling.getStatus().equals(1)) {
                                mapResult.put("signCode", "10022");
                                mapResult.put("signResult", "考勤失败");
                                return new Result(Code.FACE_ERROR, mapResult, "超过签退时间");
                            }else if (faceGetScheduling.getType().equals(8) && faceGetScheduling.getStatus().equals(1)) {
                                //交卷
                                UpdateWrapper<StudentSignIn> updateWrapper = new UpdateWrapper<>();
                                updateWrapper.eq("student_id", student.getId());
                                updateWrapper.eq("scheduling_detail_id",faceGetScheduling.getSchedulingDetailId());
                                updateWrapper.set("brush_date_time",LocalDateTime.now().withNano(0));
                                updateWrapper.set("brush_oss_image",ossImageUrl);
                                iStudentSignInService.update(updateWrapper);
                                UpdateWrapper<StudentSignInTemp> updateWrapperTemp = new UpdateWrapper<>();
                                updateWrapperTemp.eq("student_id", student.getId());
                                updateWrapperTemp.eq("scheduling_detail_id",faceGetScheduling.getSchedulingDetailId());
                                updateWrapperTemp.set("brush_date_time",LocalDateTime.now().withNano(0));
                                updateWrapperTemp.set("brush_oss_image",ossImageUrl);
                                iStudentSignInTempService.update(updateWrapperTemp);
                                mapResult.put("signCode", "10101");
                                mapResult.put("signResult", "交卷成功");
                                return new Result(Code.OK, mapResult,  "交卷成功");
                            }else if (faceGetScheduling.getType().equals(9) && faceGetScheduling.getStatus().equals(1)) {
                                //type:1：签到，2：签退，3：已签到，4：已签退，5：还未到签到时间，6：还未到签退时间,7：超过签退时间,8：刷题交卷，9：签到20分钟后交卷时间,10：交卷5分钟后才能签退，11：已交卷
                                mapResult.put("signCode", "10102");
                                mapResult.put("signResult", "交卷失败");
                                return new Result(Code.OK, mapResult,  "签到20分钟后才能交卷");
                            }else if (faceGetScheduling.getType().equals(10) && faceGetScheduling.getStatus().equals(1)) {
                                mapResult.put("signCode", "10101");
                                mapResult.put("signResult", "交卷成功");
                                return new Result(Code.OK, mapResult,  "交卷5分钟后才能签退");

                            }else if (faceGetScheduling.getType().equals(11) && faceGetScheduling.getStatus().equals(1)) {
                                mapResult.put("signCode", "10101");
                                mapResult.put("signResult", "交卷成功");
                                return new Result(Code.OK, mapResult,  "交卷成功");
                            } else {
                                mapResult.put("signCode", "10102");
                                mapResult.put("signResult", "考勤失败");
                                return new Result(Code.FACE_ERROR, mapResult, faceGetScheduling.getCourseName() + "，今日已经刷脸签到和签退，不要重复刷脸");
                            }

                            //1签到，2是签退
                            mapResult.put("signType", signType);
                            //添加到签到记录
                            iStudentSignInService.fnSaveOrUpdate(faceGetScheduling,student,ossImageUrl,dateTimeNow);
                            /***************************************微信推送***************************************************/
                            try {
                                if (signType.equals(1) || signType.equals(2)){
                                    String classTypeIdKey = "studentSignInWecharPush::"+""+student.getId()+faceGetScheduling.getSchedulingDetailId()+""+signType;
                                    Object studentSignInObj = redisTemplate.opsForValue().get(classTypeIdKey);
                                    if (Objects.isNull(studentSignInObj)) {
                                        List<String> opendIdList = iWecharsBindService.getSendOpenid(student.getId());
                                        StringBuilder first = new StringBuilder();
                                        String keyword1 = student.getName();
                                        StringBuilder keyword2 = new StringBuilder();
                                        keyword2.append(localDateTime.toString().replace("T", " "));
                                        StringBuilder keyword3 = new StringBuilder();

                                        String pushName = faceGetScheduling.getSubjectsName();
                                        if (faceGetScheduling.getLessonType()!=null){
                                            pushName += CommonUtil.getLessonTypeName(faceGetScheduling.getLessonType());
                                        }

                                        if (signType.equals(1)) {
                                            first.append(student.getName() + "已安全到校，请放心哦~");
                                            keyword3.append("【"+pushName+"】到校");
                                        } else {
                                            first.append(student.getName() + "," + faceGetScheduling.getSubjectsName() + "已下课");
                                            keyword3.append("【"+pushName+"】离校");
                                        }

                                        StringBuilder remark = new StringBuilder();
                                        remark.append("");
                                        //String url = "http://parent.5ixmy.xyz/remind/details?recordCourseId="+recordCourseId;
                                        String url = "";
                                        iWecharsBindService.onOffSchool(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), remark.toString(), url,localDateTime + "" + student.getId());
                                        redisTemplate.opsForValue().set(classTypeIdKey,faceGetScheduling.getSchedulingDetailId()+"-"+signType+"-"+student.getId(),10, TimeUnit.MINUTES);
                                    }
                                }
                            }catch (Exception e){}
                            /*************************************************************************************************/

                            if (signType.equals(1)) {
                                mapResult.put("signCode", "10001");
                                mapResult.put("signResult", "签到成功");
                                return new Result(Code.OK, mapResult,  "签到成功");
                            } else {
                                mapResult.put("signCode", "10002");
                                mapResult.put("signResult", "签退成功");
                                return new Result(Code.OK, mapResult,  "签退成功");
                            }

                        } else {
                            mapResult.put("id", entityId);
                            mapResult.put("imageUrl", ossImageUrl);
                            mapResult.put("signCode", "10007");
                            mapResult.put("signResult", "考勤失败");
                            return new Result(Code.FACE_ERROR, mapResult, "签到失败,没有找到学生数据");
                        }
                    } else {
                        mapResult.put("imageUrl", ossImageUrl);
                        mapResult.put("signResult", "考勤失败");
                        mapResult.put("signCode", "10008");
                        mapResult.put("signResult", "考勤失败");

                        LogRecord logRecord = new LogRecord();
                        logRecord.setContent("ossUrl:" + ossImageUrl);
                        logRecord.setRemark("匹配到的分值低，分值为:"+maxConfidence+"，faceRequestId:"+faceRequestId);
                        logRecord.setLevel(8);
                        iLogRecordService.save(logRecord);
                        float rounded = (float) (Math.round(maxConfidence * 100) / 100.0);
                        return new Result(Code.FACE_ERROR, mapResult, "没有找到人脸数据,请换个角度签到或者重新采集,识别分值为：" + rounded);
                    }

                } else {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10024");
                    mapResult.put("signResult", "考勤失败");
                    return new Result(Code.FACE_ERROR, mapResult, "签到失败,没有找到人脸数据，请先采集，再签到");
                }
            } else {
                mapResult.put("imageUrl", "");
                mapResult.put("signCode", "10009");
                mapResult.put("signResult", "考勤失败");
                return new Result(Code.FACE_ERROR, mapResult, "签到失败，请重新签到");//(图片上传不成功)
            }
        } catch (Exception e) {
            e.printStackTrace();
            mapResult.put("signCode", "50000");
            mapResult.put("imageUrl", ossImageUrl);
            mapResult.put("signResult", "考勤失败");
            LogRecord logRecord = new LogRecord();
            logRecord.setContent("ossUrl:" + ossImageUrl);
            logRecord.setRemark("人脸签到失败" + e.getMessage());
            logRecord.setLevel(5);

            String msg = e.getMessage();
            //boolean rs = a.contains("image not found face1");//image quality score not matched
            String typMsg = "";
            if (msg.contains("image not found face")) {
                typMsg = ":图片中没有人脸";
            } else if (msg.contains("image quality score not matched")) {
                typMsg = ":图片比较模糊";
            } else if (msg.contains("请检查帐号是否欠费")){
                if (schoolRand!=null){
                    typMsg = schoolRand.getAliAccount()+"帐号欠费，请联系智能部充值再签到";
                    logRecord.setRemark(schoolRand.getAliAccount()+"帐号欠费，请联系智能部充值再签到");
                    logRecord.setLevel(6);
                }else {
                    typMsg = e.getMessage();
                }
            }else {
                typMsg = e.getMessage();
            }
            iLogRecordService.save(logRecord);

            return new Result(Code.FACE_ERROR, mapResult, "签到失败" + typMsg);
        }
    }

    /**
     * 学生人脸采集
     */
    @PostMapping("/faceGather")
    @Transactional
    public Result faceGather(@RequestParam("file") MultipartFile upload, HttpServletRequest request,
                             @RequestParam("schoolId") String schoolId,
                             @RequestParam("studentId") String studentId) throws Exception {

        Integer faceType =1;//学生
        Organization schoolInfo = null;

        if (upload == null || upload.isEmpty()) {
            return new Result(Code.ERROR, "", "没有上传文件，请关闭重新打开");
        }

        if (StringUtils.isEmpty(schoolId)) {
            return new Result(Code.ERROR, "", "学校id不能为空");
        } else {
            schoolInfo = iOrganizationService.getById(schoolId);
            if (schoolInfo == null) {
                return new Result(Code.ERROR, "", "学校不存在");
            }
        }
        if (StringUtils.isEmpty(studentId)) {
            return new Result(Code.ERROR, "", "学生id不能为空");
        }
        Student student = iStudentService.getById(studentId);
        if (student == null) {
            return new Result(Code.ERROR, "", "学生不存在");
        }
        LocalDate localDate = LocalDate.now();

        Map<String, Object> mapResult = new HashMap<>();

        FaceDb faceDb = iFaceDbService.getFaceDbOne(1);

        //上传文件的位置,默认会在项目根目录找static文件夹,需手动创建,不然找到是临时路径。
        //String path = request.getSession().getServletContext().getRealPath("/uploads/"+directoryName);
        //System.out.println("path:"+path);
        //判断该路径是否存在
        String directoryName = "face-gather" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();
        String uploadUrl = uploadFileLocation + "/" + directoryName;

        File file = new File(uploadUrl);
        // 若不存在则创建该文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        //获取上传文件的后缀名
        String fileType = upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
        // 获取上传文件的名称
        //String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        //拼接图片
        String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
        String uuid = date + System.currentTimeMillis();
        String filename = uuid + fileType;
        // todo 把文件名存入数据库(此步骤省略)

        // 完成文件上传
        String ossImageUrl = "";
        try {
            upload.transferTo(new File(uploadUrl, filename));
            String filePath = uploadUrl + "/" + filename;
            String saveName = filename;
            iOssUploadService.upFile(filePath, saveName, directoryName);
            ossImageUrl = this.showImgEndpoint + "/" + directoryName + "/" + saveName;
            //System.out.println("ossImage:" + ossImageUrl);

            /*Long pid = schoolInfo.getId();
            if (!schoolInfo.getPid().equals(0)){
                pid = schoolInfo.getPid();
            }
            List<Long> schoolList = iOrganizationService.getOrganizationChidAll(pid,1);
            for (Long schoolIdChid:schoolList){
                FaceResult faceResult = iStudentFaceDataService.batchAddFaceData(faceDb.getDbName(),schoolIdChid,ossImageUrl,student);
                if (faceResult.getSignCode().equals("10001")){
                    //成功
                    StudentFaceData studentFaceData = new StudentFaceData();
                    studentFaceData.setSchoolId(Long.parseLong(schoolId));
                    studentFaceData.setStudentId(student.getId());
                    studentFaceData.setEntityId(student.getId());
                    studentFaceData.setOssImage(ossImageUrl);
                    studentFaceData.setFaceId(faceResult.getFaceId());
                    studentFaceData.setQualitieScore(faceResult.getScore());
                    studentFaceData.setImage(directoryName + "/" + filename);
                    iStudentFaceDataService.save(studentFaceData);
                }else {
                    //失败
                }
            }*/

            //是否需要人脸数据校验
            Company company = iCompanyService.getById(1L);
            boolean IsFaceDataVerify = false;
            if (company!=null){
                if (company.getIsFaceDataVerify().equals(1) || company.getIsFaceDataVerify().equals(3)){
                    IsFaceDataVerify = true;
                }
            }

            DetectFaceDataRequest detectFaceDataRequest = iAliyunFaceService.detectFace(Long.parseLong(schoolId), ossImageUrl);
            if (detectFaceDataRequest.getFaceCount().equals(0)){
                return new Result(Code.FACE_ERROR, mapResult, "没有人脸，请重新采集");
            }
            if (detectFaceDataRequest.getFaceCount()>1){
                if (IsFaceDataVerify){
                    return new Result(Code.FACE_ERROR, mapResult, "摄像头里不能超过1个人脸，请重新采集");
                }
            }
            if (detectFaceDataRequest.getPostNum()<60){
                return new Result(Code.FACE_ERROR, mapResult, "请把脸正对着摄相头重新采集");
            }
            if (detectFaceDataRequest.getBlurNum()<50){
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("图片过于模糊，请重新采集");
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                //return new Result(Code.FACE_ERROR, mapResult, "图片过于模糊，请重新采集");
            }
            if (detectFaceDataRequest.getSynthScore()<60){
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("采集失败，图片不符合要求，请重新采集");
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                return new Result(Code.FACE_ERROR, mapResult, "采集失败，图片不符合要求，请重新采集");
            }

            String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), Long.parseLong(schoolId), ossImageUrl);

            FaceDetectLivingRequest faceDetectLivingRequest = iAliyunFaceService.detectLivingFace(Long.parseLong(schoolId),ossImageUrl);
            if (!faceDetectLivingRequest.isLiving()){
                mapResult.put("imageUrl", ossImageUrl);
                mapResult.put("signCode", "10003");
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("人脸签到失败，不能使用照片采集"+faceDetectLivingRequest.getScore());
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                return new Result(Code.FACE_ERROR, mapResult, "不能使用照片签到，或换个背景签到");
            }

            if (faceIdAndentityId != null && !faceIdAndentityId.equals("error")) {

                String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
                String faceId = faceIdAndEntityIdArr[0];
                String entityId = faceIdAndEntityIdArr[1];
                if (studentId != entityId) {
                    Student studentEntity = iStudentService.getById(entityId);
                    //姓名相同则为同一人
                    if (studentEntity != null && student.getName().trim().equals(studentEntity.getName().trim())){
                        //修改学生状态
                        student.setHeadImg(ossImageUrl);
                        student.setIsGather(1);
                        student.setEntityId(entityId);
                        iStudentService.updateById(student);

                        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
                        studentFaceDataQueryWrapper.eq("school_id", schoolId);
                        studentFaceDataQueryWrapper.eq("student_id", student.getId());
                        studentFaceDataQueryWrapper.eq("entity_id", entityId);
                        studentFaceDataQueryWrapper.last("limit 1");
                        StudentFaceData studentFaceData = iStudentFaceDataService.getOne(studentFaceDataQueryWrapper);

                        StudentFaceData studentFaceDataAdd = new StudentFaceData();
                        studentFaceDataAdd.setSchoolId(Long.parseLong(schoolId));
                        studentFaceDataAdd.setStudentId(student.getId());
                        studentFaceDataAdd.setEntityId(Long.parseLong(entityId));
                        studentFaceDataAdd.setFaceType(faceType);
                        studentFaceDataAdd.setOssImage(ossImageUrl);
                        studentFaceDataAdd.setImage(directoryName + "/" + filename);
                        if (studentFaceData != null) {
                            studentFaceDataAdd.setFaceId(studentFaceData.getFaceId());
                            studentFaceDataAdd.setQualitieScore(studentFaceData.getQualitieScore());
                        } else {
                            studentFaceDataAdd.setFaceId(faceId);
                        }
                        iStudentFaceDataService.save(studentFaceDataAdd);

                        //添加到多人脸库
                        iStudentFaceManyDetailService.addDataBatch(studentFaceDataAdd,Long.parseLong(schoolId),faceType);

                        if (!student.getStuType().equals(2)){
                            //不为试听学员时调用合并
                            iMqPushService.studentMerge(student.getId());
                        }
                        mapResult.put("signCode", "10001");
                        return new Result(Code.OK, mapResult, "人脸采集成功");
                    }
                }
            } else if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
                mapResult.put("signCode", "10002");
                LogRecord logRecord = new LogRecord();

                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("人脸采集失败：" + student.getName());
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                return new Result(Code.FACE_ERROR, mapResult, "人脸采集失败,请重新采集");
            }

            if (iAliyunFaceService.existFaceSample(Long.parseLong(schoolId), faceDb.getDbName(), student.getId().toString())) {
                iAliyunFaceService.updateFaceSample(Long.parseLong(schoolId), faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
            } else {
                iAliyunFaceService.addFaceSample(Long.parseLong(schoolId), faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
            }

            student.setIsGather(1);//设置为已采集
            QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();

            studentFaceDataQueryWrapper.eq("school_id", schoolId);
            studentFaceDataQueryWrapper.eq("student_id", student.getId());
            studentFaceDataQueryWrapper.eq("entity_id", student.getId());
            studentFaceDataQueryWrapper.orderByAsc("created_at");
            List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);

            AddFaceResponse addFaceResponse = null;
            String extraData = student.getName().trim();
            if (studentFaceDataList.size() >= 5) {
                StudentFaceData studentFaceData = studentFaceDataList.get(0);
                studentFaceData.getEntityId();
                if (studentFaceData.getFaceId() != null) {
                    iAliyunFaceService.delFaceData(Long.parseLong(schoolId), faceDb.getDbName(), studentFaceData.getFaceId().toString());
                    iStudentFaceDataService.removeById(studentFaceData.getId());
                    addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId), faceDb.getDbName(), ossImageUrl, student.getId().toString(), extraData,faceType);//添加人脸数据
                    //System.out.println("addFaceResponse2");
                    //System.out.println(addFaceResponse);
                }
            } else {
                addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId), faceDb.getDbName(), ossImageUrl, student.getId().toString(), extraData,faceType);//添加人脸数据
                //System.out.println("addFaceResponse");
                //System.out.println(addFaceResponse);
            }
            if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
                StudentFaceData studentFaceData = new StudentFaceData();
                studentFaceData.setSchoolId(Long.parseLong(schoolId));
                studentFaceData.setStudentId(student.getId());
                studentFaceData.setEntityId(student.getId());
                studentFaceData.setOssImage(ossImageUrl);
                studentFaceData.setFaceId(addFaceResponse.getBody().getData().faceId);
                studentFaceData.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                studentFaceData.setImage(directoryName + "/" + filename);
                iStudentFaceDataService.save(studentFaceData);

                //添加到多人脸库
                iStudentFaceManyDetailService.addDataBatch(studentFaceData,Long.parseLong(schoolId),faceType);

                //修改学生状态
                student.setHeadImg(ossImageUrl);
                student.setIsGather(1);
                student.setEntityId(student.getId().toString());
                iStudentService.updateById(student);
                mapResult.put("signCode", "10001");
                return new Result(Code.OK, mapResult, "人脸采集成功");
            } else {
                if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                    mapResult.put("signCode", "10002");
                    LogRecord logRecord = new LogRecord();
                    logRecord.setContent("ossUrl:" + ossImageUrl);
                    logRecord.setRemark("人脸采集失败：" + student.getName());
                    logRecord.setLevel(5);
                    iLogRecordService.save(logRecord);
                    return new Result(Code.FACE_ERROR, "", "人脸采集失败,重新采集");
                } else {
                    mapResult.put("signCode", "10002");
                    LogRecord logRecord = new LogRecord();
                    logRecord.setContent("ossUrl:" + ossImageUrl);
                    logRecord.setRemark("人脸采集失败：" + student.getName());
                    logRecord.setLevel(5);
                    iLogRecordService.save(logRecord);
                    return new Result(Code.FACE_ERROR, "", "人脸采集失败,重新采集（没有采集到数据）");
                }
            }
        } catch (Exception e) {
            System.out.println("singCodeError");
            System.out.println(e.getMessage());
            e.printStackTrace();
            mapResult.put("signCode", "50000");
            //System.out.println("ossImageUrlError:"+ossImageUrl);
            LogRecord logRecord = new LogRecord();
            logRecord.setContent("ossUrl:" + ossImageUrl);
            logRecord.setRemark("人脸采集失败：" + student.getName());
            logRecord.setLevel(5);
            iLogRecordService.save(logRecord);
            String msg = e.getMessage();
            String typMsg = "";
            if (msg.contains("image not found face")) {
                typMsg = ":图片中没有人脸";
            } else if (msg.contains("image quality score not matched")) {
                typMsg = ":图片比较模糊";
            }else if (msg.contains("请检查帐号是否欠费")){
                Organization schoolRand = iOrganizationService.getById(schoolId);
                if (schoolRand!=null){
                    typMsg = schoolRand.getAliAccount()+"帐号欠费，请联系智能部充值再采集";
                    logRecord.setRemark(schoolRand.getAliAccount()+"帐号欠费，请先充值再签到");
                    logRecord.setLevel(6);
                }else {
                    typMsg = e.getMessage();
                }
            } else {
                typMsg = e.getMessage();
            }
            return new Result(Code.FACE_ERROR, mapResult, "人脸采集失败" + typMsg);
        }
    }

    /**
     * 教师人脸采集
     * @param upload
     * @param request
     * @param schoolId 默认使用海府校区
     * @param teacherId
     * @return
     * @throws Exception
     */
    @PostMapping("/faceGatherTeacher")
    @Transactional
    public Result faceGatherTeacher(@RequestParam("file") MultipartFile upload, HttpServletRequest request,
                                    @RequestParam(value = "schoolId",required = false,defaultValue = "1600459368801542145") String schoolId,
                                    @RequestParam("teacherId") String teacherId) throws Exception {

        Integer faceType =2;//老师
        Organization schoolInfo = null;

        if (upload == null || upload.isEmpty()) {
            return new Result(Code.ERROR, "", "没有上传文件，请关闭重新打开");
        }

        if (StringUtils.isEmpty(schoolId)) {
            return new Result(Code.ERROR, "", "学校id不能为空");
        } else {
            schoolInfo = iOrganizationService.getById(schoolId);
            if (schoolInfo == null) {
                return new Result(Code.ERROR, "", "学校不存在");
            }
        }
        if (StringUtils.isEmpty(teacherId)) {
            return new Result(Code.ERROR, "", "老师id不能为空");
        }
        Staff teacherInfo = staffMapper.selectById(teacherId);
        if (teacherInfo == null) {
            return new Result(Code.ERROR, "", "老师不存在");
        }
        LocalDate localDate = LocalDate.now();

        Map<String, Object> mapResult = new HashMap<>();

        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);

        //上传文件的位置,默认会在项目根目录找static文件夹,需手动创建,不然找到是临时路径。
        //String path = request.getSession().getServletContext().getRealPath("/uploads/"+directoryName);
        //System.out.println("path:"+path);
        //判断该路径是否存在
        String directoryName = "face-gather" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();
        String uploadUrl = uploadFileLocation + "/" + directoryName;

        File file = new File(uploadUrl);
        // 若不存在则创建该文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        //获取上传文件的后缀名
        String fileType = upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
        // 获取上传文件的名称
        //String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        //拼接图片
        String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
        String uuid = date + System.currentTimeMillis();
        String filename = uuid + fileType;
        // todo 把文件名存入数据库(此步骤省略)

        // 完成文件上传
        String ossImageUrl = "";
        try {
            upload.transferTo(new File(uploadUrl, filename));
            String filePath = uploadUrl + "/" + filename;
            String saveName = filename;
            iOssUploadService.upFile(filePath, saveName, directoryName);
            ossImageUrl = this.showImgEndpoint + "/" + directoryName + "/" + saveName;

            //是否需要人脸数据校验
            Company company = iCompanyService.getById(1L);
            boolean IsFaceDataVerify = false;
            if (company!=null){
                if (company.getIsFaceDataVerify().equals(1) || company.getIsFaceDataVerify().equals(3)){
                    IsFaceDataVerify = true;
                }
            }

            DetectFaceDataRequest detectFaceDataRequest = iAliyunFaceService.detectFace(Long.parseLong(schoolId), ossImageUrl);
            if (detectFaceDataRequest.getFaceCount().equals(0)){
                return new Result(Code.FACE_ERROR, mapResult, "没有人脸，请重新采集");
            }
            if (detectFaceDataRequest.getFaceCount()>1){
                if (IsFaceDataVerify){
                    return new Result(Code.FACE_ERROR, mapResult, "摄像头里不能超过1个人脸，请重新采集");
                }
            }
            if (detectFaceDataRequest.getPostNum()<60){
                return new Result(Code.FACE_ERROR, mapResult, "请把脸正对着摄相头重新采集");
            }
            if (detectFaceDataRequest.getBlurNum()<50){
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("图片过于模糊，请重新采集");
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                //return new Result(Code.FACE_ERROR, mapResult, "图片过于模糊，请重新采集");
            }
            if (detectFaceDataRequest.getSynthScore()<60){
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("采集失败，图片不符合要求，请重新采集");
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                return new Result(Code.FACE_ERROR, mapResult, "采集失败，图片不符合要求，请重新采集");
            }

            String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), Long.parseLong(schoolId), ossImageUrl);

            FaceDetectLivingRequest faceDetectLivingRequest = iAliyunFaceService.detectLivingFace(Long.parseLong(schoolId),ossImageUrl);
            if (!faceDetectLivingRequest.isLiving()){
                mapResult.put("imageUrl", ossImageUrl);
                mapResult.put("signCode", "10003");
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("人脸签到失败，不能使用照片采集"+faceDetectLivingRequest.getScore());
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                return new Result(Code.FACE_ERROR, mapResult, "不能使用照片签到，或换个背景签到");
            }

            if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
                mapResult.put("signCode", "10002");
                LogRecord logRecord = new LogRecord();

                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("人脸采集失败：" + teacherInfo.getName());
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                return new Result(Code.FACE_ERROR, mapResult, "人脸采集失败,请重新采集");
            }

            if (iAliyunFaceService.existFaceSample(Long.parseLong(schoolId), faceDb.getDbName(), teacherInfo.getId().toString())) {
                iAliyunFaceService.updateFaceSample(Long.parseLong(schoolId), faceDb.getDbName(), teacherInfo.getId().toString(), teacherInfo.getName());//添加人脸样本
            } else {
                iAliyunFaceService.addFaceSample(Long.parseLong(schoolId), faceDb.getDbName(), teacherInfo.getId().toString(), teacherInfo.getName());//添加人脸样本
            }

            QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();

            studentFaceDataQueryWrapper.eq("school_id", schoolId);
            studentFaceDataQueryWrapper.eq("student_id", teacherInfo.getId());
            studentFaceDataQueryWrapper.eq("entity_id", teacherInfo.getId());
            studentFaceDataQueryWrapper.orderByAsc("created_at");
            List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);

            AddFaceResponse addFaceResponse = null;
            String extraData = teacherInfo.getName().trim();
            if (studentFaceDataList.size() >= 5) {
                StudentFaceData studentFaceData = studentFaceDataList.get(0);
                studentFaceData.getEntityId();
                if (studentFaceData.getFaceId() != null) {
                    iAliyunFaceService.delFaceData(Long.parseLong(schoolId), faceDb.getDbName(), studentFaceData.getFaceId().toString());
                    iStudentFaceDataService.removeById(studentFaceData.getId());
                    addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId), faceDb.getDbName(), ossImageUrl, teacherInfo.getId().toString(), extraData,faceType);//添加人脸数据
                    //System.out.println("addFaceResponse2");
                    //System.out.println(addFaceResponse);
                }
            } else {
                addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId), faceDb.getDbName(), ossImageUrl, teacherInfo.getId().toString(), extraData,faceType);//添加人脸数据
                //System.out.println("addFaceResponse");
                //System.out.println(addFaceResponse);
            }
            if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
                StudentFaceData studentFaceData = new StudentFaceData();
                studentFaceData.setSchoolId(Long.parseLong(schoolId));
                studentFaceData.setStudentId(teacherInfo.getId());
                studentFaceData.setEntityId(teacherInfo.getId());
                studentFaceData.setOssImage(ossImageUrl);
                studentFaceData.setFaceId(addFaceResponse.getBody().getData().faceId);
                studentFaceData.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                studentFaceData.setImage(directoryName + "/" + filename);
                iStudentFaceDataService.save(studentFaceData);

                //添加到多人脸库
                iStudentFaceManyDetailService.addDataBatch(studentFaceData,Long.parseLong(schoolId),faceType);

                //修改老师状态
                teacherInfo.setHeadImg(ossImageUrl);
                teacherInfo.setIsGather(1);
                staffMapper.updateById(teacherInfo);
                mapResult.put("signCode", "10001");
                return new Result(Code.OK, mapResult, "人脸采集成功");
            } else {
                if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                    mapResult.put("signCode", "10002");
                    LogRecord logRecord = new LogRecord();
                    logRecord.setContent("ossUrl:" + ossImageUrl);
                    logRecord.setRemark("人脸采集失败：" + teacherInfo.getName());
                    logRecord.setLevel(5);
                    iLogRecordService.save(logRecord);
                    return new Result(Code.FACE_ERROR, "", "人脸采集失败,重新采集");
                } else {
                    mapResult.put("signCode", "10002");
                    LogRecord logRecord = new LogRecord();
                    logRecord.setContent("ossUrl:" + ossImageUrl);
                    logRecord.setRemark("人脸采集失败：" + teacherInfo.getName());
                    logRecord.setLevel(5);
                    iLogRecordService.save(logRecord);
                    return new Result(Code.FACE_ERROR, "", "人脸采集失败,重新采集（没有采集到数据）");
                }
            }
        } catch (Exception e) {
            System.out.println("singCodeError");
            System.out.println(e.getMessage());
            e.printStackTrace();
            mapResult.put("signCode", "50000");
            //System.out.println("ossImageUrlError:"+ossImageUrl);
            LogRecord logRecord = new LogRecord();
            logRecord.setContent("ossUrl:" + ossImageUrl);
            logRecord.setRemark("人脸采集失败：" + teacherInfo.getName());
            logRecord.setLevel(5);
            iLogRecordService.save(logRecord);
            String msg = e.getMessage();
            String typMsg = "";
            if (msg.contains("image not found face")) {
                typMsg = ":图片中没有人脸";
            } else if (msg.contains("image quality score not matched")) {
                typMsg = ":图片比较模糊";
            }else if (msg.contains("请检查帐号是否欠费")){
                Organization schoolRand = iOrganizationService.getById(schoolId);
                if (schoolRand!=null){
                    typMsg = schoolRand.getAliAccount()+"帐号欠费，请联系智能部充值再采集";
                    logRecord.setRemark(schoolRand.getAliAccount()+"帐号欠费，请先充值再签到");
                    logRecord.setLevel(6);
                }else {
                    typMsg = e.getMessage();
                }
            } else {
                typMsg = e.getMessage();
            }
            return new Result(Code.FACE_ERROR, mapResult, "人脸采集失败" + typMsg);
        }
    }




    /**
     * 查看签到记录
     *
     * @param schoolId
     * @param gradeId
     * @param
     * @return
     */
    @GetMapping("/signInLog")
    public Result signInLog(@RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                            @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                            @RequestParam(value = "gradeId", required = false, defaultValue = "") String gradeId,
                            @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId,
                            @RequestParam(value = "timeStart", required = false, defaultValue = "") String timeStart,
                            @RequestParam(value = "timeEnd", required = false, defaultValue = "") String timeEnd,
                            @RequestParam(value = "signStatus", required = false, defaultValue = "") String signStatus,
                            @RequestParam(value = "lessonType", required = false, defaultValue = "") String lessonType,
                            @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                            @RequestParam(value = "studentName", required = false, defaultValue = "") String studentName,
                            @RequestParam(value = "timeStartAndEnd", required = false, defaultValue = "") String timeStartAndEnd
    ) {
        Map<String, Object> mapResult = new HashMap<>();

        if (StringUtils.isBlank(schoolId)) {
            return new Result(Code.ERROR, "", "请选择刷脸校区");
        }

        LocalDate nowDate = LocalDate.now();

        Quarter quarter = iQuarterService.getNowQuarter();
        if (quarter == null) {
            throw new CommonException(ResultCode.quarterNo);
        }
        String status = "";
        if (StringUtils.isNotBlank(signStatus)) {
            status = signStatus.equals("1") ? signStatus : "0";
        }

        String type = "1";//个人

        Integer lessonTypeP = StringUtils.isNotBlank(lessonType) ? Integer.parseInt(lessonType) : null;

        List<RecordCourse> startAndEndList = null;
        if (StringUtils.isNotBlank(timeStartAndEnd)){
            startAndEndList = new ArrayList<>();
            String[] timeStartAndEndArr = timeStartAndEnd.split(",");
            for (String timeStr : timeStartAndEndArr) {
                String[] timeArr = timeStr.split("-");
                RecordCourse recordCourse = new RecordCourse();
                recordCourse.setTimeStart(timeArr[0]);
                recordCourse.setTimeEnd(timeArr[1]);
                startAndEndList.add(recordCourse);
            }
        }

        List<SignResult> recordCourseList = iCourseSchedulingDetailService.signInDetail(schoolId, subjectsId, quarter.getYearPart().toString(), quarter.getNum().toString(), nowDate.toString(), nowDate.toString(), gradeId, teacherId, type, status, timeStart, timeEnd, lessonTypeP, classTypeId,studentName,false,startAndEndList);

        mapResult.put("signCode", "20000");
        mapResult.put("signList", recordCourseList);
        return new Result(Code.OK, mapResult, "");
    }

    @GetMapping("/schedulingTeacher")
    public Result schedulingTeacher(@RequestParam("schoolIdList") String schoolId){
        if (StringUtils.isBlank(schoolId)) {
            if (this.baseSchoolIdList.size() > 0)
                schoolId = this.baseSchoolIdList.get(0).toString();
            else
                schoolId = "0";
        }

        LocalDate nowDate = LocalDate.now();
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        repairCourseQueryWrapper.eq("school_date", nowDate);
        repairCourseQueryWrapper.eq("school_id", schoolId);
        repairCourseQueryWrapper.eq("deleted", 0);
        repairCourseQueryWrapper.groupBy("teacher_id");
        repairCourseQueryWrapper.orderByAsc("start_date_time");
        List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingUnionRepair(repairCourseQueryWrapper);
        List<Staff> staffList = new ArrayList<>();
        for (RepairCourse repairCourse : repairCourseList) {
            Staff staff = new Staff();
            staff.setId(repairCourse.getTeacherId());
            staff.setName(repairCourse.getTeacherName());
            staffList.add(staff);
        }
        return new Result(Code.OK, new PageResult(staffList, (long) staffList.size(), 1L));
    }


    @GetMapping("/schedulingGrade")
    public Result schedulingGrade(@RequestParam("schoolIdList") String schoolId,
                                  @RequestParam("teacherId") String teacherId) {

        if (StringUtils.isBlank(schoolId)) {
            if (this.baseSchoolIdList.size() > 0)
                schoolId = this.baseSchoolIdList.get(0).toString();
            else
                schoolId = "0";
        }

        LocalDate nowDate = LocalDate.now();
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        repairCourseQueryWrapper.eq("school_date", nowDate);
        repairCourseQueryWrapper.eq("school_id", schoolId);
        repairCourseQueryWrapper.eq("teacher_id", teacherId);
        repairCourseQueryWrapper.eq("deleted", 0);
        repairCourseQueryWrapper.groupBy("grade_id");
        //repairCourseQueryWrapper.and(i->i.inSql("grade_id","select grade_id from student_grade where school_id = "+schoolId+" and status = 1 and reading_status=1 and year_part = "+quarter.getYearPart()+" and quarter_num="+quarter.getNum()+" and student_id = "+studentId+" ").eq("scheduling_type",1).or(j->j.eq("student_id",studentId).eq("scheduling_type",2)));
        //SrepairCourseQueryWrapper.notInSql("id","select IFNULL(out_scheduling_detail_id,0) from repair_course where deleted=0 and course_type=4 and school_id = "+schoolId+" and year_part = "+quarter.getYearPart()+" and quarter="+quarter.getNum()+" and student_id = "+studentId+"");//排除已经调课出去的
        repairCourseQueryWrapper.orderByAsc("start_date_time");
        List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingUnionRepair(repairCourseQueryWrapper);
        List<Grade> gradeList = new ArrayList<>();
        for (RepairCourse repairCourse : repairCourseList) {
            Grade grade = iGradeService.getById(repairCourse.getGradeId());
            if (grade == null) {
                //System.out.println("gradeId:" + repairCourse.getGradeId());
                continue;
            }
            gradeList.add(grade);
        }
        return new Result(Code.OK, new PageResult(gradeList, (long) gradeList.size(), 1L));

    }


    @GetMapping("/getSchoolTime")
    public Result getSchoolTime(@RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                @RequestParam(value = "gradeId", required = false, defaultValue = "") String gradeId,
                                @RequestParam(value = "teacherId", required = false, defaultValue = "") String teacherId,
                                @RequestParam(value = "lessonType", required = false, defaultValue = "") String lessonType) {

        LocalDate localDateNow = LocalDate.now();
        List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchoolDateList(schoolId, gradeId, teacherId, localDateNow.toString(), lessonType);
        return new Result(Code.GET_OK, new PageResult(repairCourseList, (long) repairCourseList.size(), 1L), "获取成功");
    }

    @GetMapping("/upload")
    public Result upload() {
        String filePath = "";
        String saveName = "";
        String directoryName = "face-gather";
        iOssUploadService.upFile(filePath, saveName, directoryName);
        return new Result(Code.OK);
    }

    /**
     * 是否在线
     *
     * @return
     */
    @GetMapping("/isOnline")
    public Result isOnline() {
        return new Result(Code.OK);
    }


    @GetMapping("/faceDataInit")
    public Result faceDataInit(
            @RequestParam(value = "studentId", defaultValue = "studentId") String studentId,
            @RequestParam(value = "pageSize", defaultValue = "100000") Integer pageSize) throws InterruptedException {
        iStudentFaceDataService.addFaceDataManyDetailInit(studentId,pageSize,null);
        return new Result(Code.FACE_ERROR, "", "更新中");
    }

    @GetMapping("/faceDataManyForStudentId")
    public Result faceDataManyForStudentId(@RequestParam(value = "studentId") Long studentId,
                                           @RequestParam(value = "faceType") Integer faceType) throws Exception {
        iStudentFaceDataService.faceDataManyForStudentId(studentId,faceType);
        return new Result(Code.FACE_ERROR, "", "更新中");
    }

    @PostMapping("/signInTest")
    public Result signInTest(
            @RequestParam(value = "schoolId",required = false) Long schoolId,
            @RequestParam(value = "studentId",required = false) Long studentId,
            @RequestParam(value = "subjectsId",required = false) String subjectsId,
            @RequestParam(value = "schoolSiteId",required = false) String schoolSiteId
    ) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

        if(quarterNow == null){
            throw new CommonException(ResultCode.quarterNo);
        }

        Integer lessonType =1;
        Staff staff = iStaffService.getOneById(this.adminId);
        if (StringUtils.isBlank(subjectsId)){
            List<String> stringList = iStaffService.getSiginSubjects(staff,lessonType);
            if (stringList.size() ==1){
                subjectsId = stringList.get(0);
            }else {
                return new Result(Code.ERROR, "", "请先选择签到的科目");
            }
        }
        //非任课老师
        if (!staff.getIsTeacher().equals(1)){
            if (subjectsId.equals("1")){
                lessonType = 2;//智能课
            }else{
                lessonType = 3;//刷题班
            }
        }
        //是否需要人脸数据校验
        Company company = iCompanyService.getById(1L);
        boolean IsFaceDataVerify = false;
        if (company!=null){
            if (company.getIsFaceDataVerify().equals(1) || company.getIsFaceDataVerify().equals(2)){
                IsFaceDataVerify = true;
            }
        }

        Map<String, Object> mapResult = new HashMap<>();
        String ossImageUrl = "";
        try {
            //找到的学生
            List<Student> studentList = new ArrayList<>();

            Student student = iStudentService.getById(studentId);
            studentList.add(student);

            if (studentList.size() > 0) {
                /**
                 * 会存在多个学生，添加的查询
                 * 获取排课信息
                 */
                FaceGetScheduling faceGetScheduling = null;
                FaceGetScheduling faceGetSchedulingNext = null;
                for (Student studentInfo : studentList) {
                    if (faceGetScheduling == null) {
                        student = studentInfo;
                        faceGetScheduling = iFaceStudentService.getCourseSchedulingDetail(schoolId,this.adminId, studentInfo.getId(),subjectsId,lessonType,quarterNow);
                        faceGetScheduling.setStudentId(studentInfo.getId());
                        mapResult.put("name", studentInfo.getName());
                        mapResult.put("id", studentInfo.getId());
                        mapResult.put("studentId", studentInfo.getId());
                        List<StudentAudio> studentAudioList = iStudentAudioService.getListForStudentId(studentInfo.getId());
                        mapResult.put("nameAudioList", studentAudioList);

                        if (studentInfo.getHeadImg().isEmpty()) {
                            mapResult.put("imageUrl", ossImageUrl);
                        } else {
                            mapResult.put("imageUrl", studentInfo.getHeadImg());
                        }
                    } else if (faceGetScheduling.getIsToNext()) {
                        faceGetSchedulingNext = iFaceStudentService.getCourseSchedulingDetail(schoolId,this.adminId, studentInfo.getId(),subjectsId,lessonType,quarterNow);
                        if (faceGetSchedulingNext.getType() != null) {
                            student = studentInfo;
                            faceGetScheduling = faceGetSchedulingNext;
                            faceGetScheduling.setStudentId(studentInfo.getId());
                            mapResult.put("name", studentInfo.getName());
                            mapResult.put("id", studentInfo.getId());
                            mapResult.put("studentId", studentInfo.getId());
                            List<StudentAudio> studentAudioList = iStudentAudioService.getListForStudentId(studentInfo.getId());
                            mapResult.put("nameAudioList", studentAudioList);
                            if (studentInfo.getHeadImg().isEmpty()) {
                                mapResult.put("imageUrl", ossImageUrl);
                            } else {
                                mapResult.put("imageUrl", studentInfo.getHeadImg());
                            }
                        }
                    }
                }

                //System.out.println("=========================================");
                //System.out.println(faceGetScheduling);
                if (faceGetScheduling == null || faceGetScheduling.getStatus() == null|| faceGetScheduling.getType() == null) {
                    if (lessonType.equals(2) || lessonType.equals(3)){
                        //如果签到的是刷题班没有排课信息，添加临时上课信息
                        faceGetScheduling = iStudentSignInService.getTemporaryData(student.getId(), subjectsId,lessonType,quarterNow);
                    }else if (lessonType.equals(1)){
                        //签到是精品课，学生为试听类型，添加试听信息
                        faceGetScheduling = iStudentSignInService.getTryListenData(student,subjectsId,lessonType,quarterNow);
                    }
                }
                if (faceGetScheduling == null || faceGetScheduling.getStatus() == null|| faceGetScheduling.getType() == null) {
                    mapResult.put("signCode", "10003");
                    mapResult.put("imageUrl", ossImageUrl);
                    return new Result(Code.FACE_ERROR, mapResult, "没有找到现在要签到的排课信息");
                }else {

                }

                //获取班型
                Grade grade = iStudentGradeService.getClassTypeNameForStudentId(faceGetScheduling.getYearPart(),faceGetScheduling.getQuarterNum(),faceGetScheduling.getStudentId(),faceGetScheduling.getSubjectsId());
                String classTypeName = "";
                String teacherName = "";
                String yearClassId = "";
                if (grade !=null){
                    classTypeName = grade.getCourseTypeName();
                    teacherName = grade.getTeacherName();
                    if (grade.getYearClassId() != null){
                        yearClassId = grade.getYearClassId().getKey().toString();
                    }
                }
                mapResult.put("classTypeName",classTypeName);
                mapResult.put("teacherName",teacherName);
                mapResult.put("gradeName", faceGetScheduling.getGradeName());
                mapResult.put("subjectsId",faceGetScheduling.getSubjectsId());
                mapResult.put("lessonType",faceGetScheduling.getLessonType());
                mapResult.put("yearClassId",yearClassId);
                //1签到，2是签退
                Integer signType = 1;
                Long recordCourseId = 0L;

                //type:1签到，2签退，3已签到，，4已签退，5还未到签到时间，6还未到签退时间,7超过签退时间
                if (faceGetScheduling.getType().equals(1) && faceGetScheduling.getStatus().equals(1)) {
                    signType = 1;
                    //添加到记上课表里
                    //if(faceGetScheduling.getCourseType().equals(1)){
                    //    iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(),student.getId(),1,faceGetScheduling.getCourseType());
                    //}
                    if(!faceGetScheduling.getCourseType().equals(7) && !faceGetScheduling.getCourseType().equals(8)){
                        recordCourseId = iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(), student.getName(), 1, faceGetScheduling.getCourseType(), faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,schoolSiteId);
                        //补、调、消课、缺课补课改为到课状态
                        if (faceGetScheduling.getCourseType() != null) {
                            if (faceGetScheduling.getCourseType() == 3 || faceGetScheduling.getCourseType() == 4 || faceGetScheduling.getCourseType() == 5 || faceGetScheduling.getCourseType() == 6) {
                                RepairCourse repairCourse = iRepairCourseService.getById(faceGetScheduling.getSchedulingDetailId());
                                if (repairCourse != null) {
                                    repairCourse.setIsSignIn(1);
                                    iRepairCourseService.updateById(repairCourse);
                                }
                            }
                        }
                        if (faceGetScheduling.getSubjectsId() != null && faceGetScheduling.getSubjectsId().equals(1L)){
                            RecordCourse recordCourseAdd  = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId,student.getId(), student.getName(), 1,faceGetScheduling.getCourseType(),faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,faceGetScheduling.getSubjectsId().toString(),2);
                            LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                            recordCourseId = recordCourseAdd.getId();
                            //推送到英语学习系统分配电脑
                            iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(),faceGetScheduling.getStudentId(),student.getName(),signType,schoolSiteId,this.adminId,kickOutTime);
                        }

                    }else if (faceGetScheduling.getCourseType().equals(7)){
                        //智能课或者刷题班临时上课
                        recordCourseId = iRecordCourseService.addTemporaryData(faceGetScheduling,quarterNow,this.adminId,signType,schoolSiteId);
                        //推送到英语学习系统分配电脑
                        if (faceGetScheduling.getSubjectsId() != null && faceGetScheduling.getSubjectsId().equals(1L)){
                            RecordCourse recordCourseAdd = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId,student.getId(), student.getName(), 1,faceGetScheduling.getCourseType(),faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,faceGetScheduling.getSubjectsId().toString(),2);
                            LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                            recordCourseId = recordCourseAdd.getId();
                            //推送到英语学习系统分配电脑
                            iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(),faceGetScheduling.getStudentId(),student.getName(),signType,schoolSiteId,this.adminId,kickOutTime);
                        }
                    }else if (faceGetScheduling.getLessonType().equals(1) && faceGetScheduling.getCourseType().equals(8)){
                        //精品课试听
                        iRecordCourseService.addTryListenData(faceGetScheduling,quarterNow,this.adminId);
                    }

                } else if (faceGetScheduling.getType().equals(2) && faceGetScheduling.getStatus().equals(1)) {
                    signType = 2;
                    //if(faceGetScheduling.getCourseType().equals(1)) {
                    //    iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(), 1,faceGetScheduling.getCourseType());
                    //}
                    if(!faceGetScheduling.getCourseType().equals(7)) {
                        recordCourseId = iRecordCourseService.addForSchedulingId(faceGetScheduling.getSchedulingDetailId(), student.getId(), student.getName(), 1, faceGetScheduling.getCourseType(), faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,schoolSiteId);
                        //补、调、消课、缺课补课改为到课状态
                        if (faceGetScheduling.getCourseType() != null) {
                            if (faceGetScheduling.getCourseType() == 3 || faceGetScheduling.getCourseType() == 4 || faceGetScheduling.getCourseType() == 5 || faceGetScheduling.getCourseType() == 6) {
                                RepairCourse repairCourse = iRepairCourseService.getById(faceGetScheduling.getSchedulingDetailId());
                                if (repairCourse != null) {
                                    repairCourse.setIsSignIn(1);
                                    iRepairCourseService.updateById(repairCourse);
                                }
                            }
                        }
                    }else if (faceGetScheduling.getCourseType().equals(7)){
                        //临时上课
                        recordCourseId = iRecordCourseService.addTemporaryData(faceGetScheduling,quarterNow,this.adminId,signType,schoolSiteId);
                        //推送到英语学习系统分配电脑
                        if (faceGetScheduling.getSubjectsId() != null && faceGetScheduling.getSubjectsId().equals(1L)){
                            RecordCourse recordCourseAdd = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId,student.getId(), student.getName(), 1,faceGetScheduling.getCourseType(),faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,faceGetScheduling.getSubjectsId().toString(),2);
                            LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                            recordCourseId = recordCourseAdd.getId();
                            //推送到英语学习系统分配电脑
                            iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(),faceGetScheduling.getStudentId(),student.getName(),signType,schoolSiteId,this.adminId,kickOutTime);
                        }
                    }else if (faceGetScheduling.getLessonType().equals(1) && faceGetScheduling.getCourseType().equals(8)){
                        //精品课试听
                        iRecordCourseService.addTryListenData(faceGetScheduling,quarterNow,this.adminId);
                    }
                } else if (faceGetScheduling.getType().equals(3) && faceGetScheduling.getStatus().equals(1)) {
                    if (faceGetScheduling.getSubjectsId()!=null && faceGetScheduling.getSubjectsId().equals(1L)){
                        RecordCourse recordCourseAdd = iCourseSchedulingDetailService.addSiginScheduling(faceGetScheduling.getSchedulingDetailId(),this.adminId,student.getId(), student.getName(), 1,faceGetScheduling.getCourseType(),faceGetScheduling.getReachType(),this.adminId,dateTimeNow,signType,faceGetScheduling.getSubjectsId().toString(),2);
                        LocalDateTime kickOutTime = recordCourseAdd.getEndDateTime();
                        recordCourseId = recordCourseAdd.getId();
                        //推送到英语学习系统分配电脑
                        iAiSchoolSiteService.siginAllotPc(faceGetScheduling.getSchedulingDetailId(),faceGetScheduling.getStudentId(),student.getName(),signType,schoolSiteId,this.adminId,kickOutTime);
                    }
                    mapResult.put("signCode", "10004");
                    return new Result(Code.FACE_ERROR, mapResult, "今日已经刷脸签到，不要重复刷脸");
                } else if (faceGetScheduling.getType().equals(4) && faceGetScheduling.getStatus().equals(1)) {
                    mapResult.put("signCode", "10005");
                    return new Result(Code.FACE_ERROR, mapResult, "今日已经刷脸签退，不要重复刷脸");
                } else if (faceGetScheduling.getType().equals(5) && faceGetScheduling.getStatus().equals(1)) {
                    mapResult.put("signCode", "10006");
                    return new Result(Code.FACE_ERROR, mapResult, ",还未到签到时间");
                } else if (faceGetScheduling.getType().equals(6) && faceGetScheduling.getStatus().equals(1)) {
                    mapResult.put("signCode", "10021");
                    return new Result(Code.FACE_ERROR, mapResult, ",还未到签退时间");
                } else if (faceGetScheduling.getType().equals(7) && faceGetScheduling.getStatus().equals(1)) {
                    mapResult.put("signCode", "10022");
                    return new Result(Code.FACE_ERROR, mapResult, "超过签退时间");
                } else {
                    mapResult.put("signCode", "10023");
                    return new Result(Code.FACE_ERROR, mapResult, faceGetScheduling.getCourseName() + "，今日已经刷脸签到和签退，不要重复刷脸");
                }

                //1签到，2是签退
                mapResult.put("signType", signType);
                //添加到签到记录
                iStudentSignInService.fnSaveOrUpdate(faceGetScheduling,student,ossImageUrl,dateTimeNow);
                /***************************************微信推送***************************************************/
                List<String> opendIdList = iWecharsBindService.getSendOpenid(student.getId());
                StringBuilder first = new StringBuilder();
                String keyword1 = student.getName();
                StringBuilder keyword2 = new StringBuilder();
                keyword2.append(LocalDateTime.now().withNano(0).toString().replace("T", " "));
                StringBuilder keyword3 = new StringBuilder();

                String pushName = faceGetScheduling.getSubjectsName();
                if (faceGetScheduling.getLessonType()!=null){
                    pushName += CommonUtil.getLessonTypeName(faceGetScheduling.getLessonType());
                }

                if (signType.equals(1)) {
                    first.append(student.getName() + "已安全到校，请放心哦~");
                    keyword3.append("【"+pushName+"】到校");
                } else {
                    first.append(student.getName() + "," + faceGetScheduling.getSubjectsName() + "已下课");
                    keyword3.append("【"+pushName+"】离校");
                }

                StringBuilder remark = new StringBuilder();
                remark.append("");


                //String url = "http://parent.5ixmy.xyz/remind/details?recordCourseId="+recordCourseId;
                String url = "";
                iWecharsBindService.onOffSchool(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), remark.toString(), url,LocalDateTime.now().toString() + "" + student.getId());
                /*************************************************************************************************/

                if (signType.equals(1)) {
                    mapResult.put("signCode", "10001");
                    return new Result(Code.OK, mapResult, faceGetScheduling.getGradeName() + ",签到成功");
                } else {
                    mapResult.put("signCode", "10002");
                    return new Result(Code.OK, mapResult, faceGetScheduling.getGradeName() + ",签退成功");
                }

            } else {
                mapResult.put("id", student.getId());
                mapResult.put("imageUrl", ossImageUrl);
                mapResult.put("signCode", "10007");
                return new Result(Code.FACE_ERROR, mapResult, "签到失败,没有找到学生数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            mapResult.put("signCode", "50000");
            mapResult.put("imageUrl", ossImageUrl);
            LogRecord logRecord = new LogRecord();
            logRecord.setContent("ossUrl:" + ossImageUrl);
            logRecord.setRemark("人脸签到失败" + e.getMessage());
            logRecord.setLevel(5);
            iLogRecordService.save(logRecord);
            String msg = e.getMessage();
            //boolean rs = a.contains("image not found face1");//image quality score not matched
            String typMsg = "";
            if (msg.contains("image not found face")) {
                typMsg = ":图片中没有人脸";
            } else if (msg.contains("image quality score not matched")) {
                typMsg = ":图片比较模糊";
            } else {
                typMsg = e.getMessage();
            }
            return new Result(Code.FACE_ERROR, mapResult, "签到失败" + typMsg);
        }
    }

    @GetMapping("/testRedis")
    public Result testRedis(@RequestParam("schedulingDetailId") Long schedulingDetailId,
                            @RequestParam("signType") Long signType
    ){
        Long entityId = 1904540553152823296L;
        String classTypeIdKey = "studentSignIn::"+entityId;
        Object studentSignInObj = redisTemplate.opsForValue().get(classTypeIdKey);
        if (Objects.isNull(studentSignInObj)) {
            List<Long> studentIdList = new ArrayList<>();
            studentIdList.add(1904540553152823296L);
            studentIdList.add(1904539501246545920L);
            studentIdList.add(1904533481493364736L);

            List<Student> studentList = new ArrayList<>();
            for (Long studentId:studentIdList) {
                Student studentInfo = iStudentService.getById(studentId);
                studentList.add(studentInfo);
            }
            redisTemplate.opsForValue().set(classTypeIdKey,studentList,1, TimeUnit.MINUTES);
            return new Result(Code.OK, studentSignInObj, "");
        }else {


            List<Student> studentList = (List<Student>) studentSignInObj;
            System.out.println(studentList);
            return new Result(Code.OK, studentList, "");
        }
    }
}

